package com.museum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.museum.entity.SystemSettings;
import com.museum.mapper.SystemSettingsMapper;
import com.museum.service.SystemSettingsService;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Primary
public class SystemSettingsServiceImpl extends ServiceImpl<SystemSettingsMapper, SystemSettings> implements SystemSettingsService {

    @Override
    public SystemSettings getSettings() {
        // 获取系统设置，默认获取ID最大的一条记录
        LambdaQueryWrapper<SystemSettings> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(SystemSettings::getId);
        wrapper.last("LIMIT 1");
        
        SystemSettings settings = getOne(wrapper);
        
        // 如果没有设置记录，则创建默认设置
        if (settings == null) {
            settings = new SystemSettings();
            settings.setMuseumName("博物馆");
            settings.setOpenTime("周二至周日 9:00-17:00");
            settings.setContactPhone("12345678901");
            settings.setAddress("博物馆地址");
            settings.setMaxReservation(200);
            settings.setCreateTime(LocalDateTime.now());
            settings.setUpdateTime(LocalDateTime.now());
            save(settings);
        }
        
        return settings;
    }
    
    @Override
    public boolean updateSettings(SystemSettings settings) {
        if (settings.getId() == null) {
            // 如果没有ID，则获取当前设置
            SystemSettings currentSettings = getSettings();
            settings.setId(currentSettings.getId());
        }
        
        settings.setUpdateTime(LocalDateTime.now());
        return updateById(settings);
    }
}